﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace BasicData.Infastruucture
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly MyContext context;

        public BaseRepository(MyContext context)
        {
            this.context = context;
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public Task<int> AddRangeAsync(IEnumerable<T> list)
        {
           context.Set<T>().AddRangeAsync(list);
            return context.SaveChangesAsync();
        }

        public int Create(T t)
        {
            context.Set<T>().Add(t);
            return context.SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int Delete(T t)
        {
            context.Set<T>().Remove(t);
            return context.SaveChanges();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int DeleteAnage(Expression<Func<T, bool>> predicate)
        {
           var res=context.Set<T>().Where(predicate);
            context.Set<T>().RemoveRange(res);
            return context.SaveChanges();
        }

        public IQueryable<T> GetAll()
        {
            return context.Set<T>();
        }

        public T GetByModel(long id)
        {
            return context.Set<T>().Find(id);
        }

        public int Update(T t)
        {
            context.Set<T>().Update(t);
            return context.SaveChanges();
        }
    }
}
